package com.pig.graduate.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig.graduate.common.constant.Constant;
import com.pig.graduate.domain.sys.SysMenu;
import com.pig.graduate.domain.sys.SysRole;
import com.pig.graduate.domain.sys.SysUser;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.sys.SysMenuService;
import com.pig.graduate.service.sys.SysRoleService;
import com.pig.graduate.service.sys.SysUserService;
import com.pig.graduate.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.util.*;

/**
 * 系统菜单Controller控制器
 */
@Api(tags = {"系统菜单"}, description = "系统菜单")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 获取当前用户的导航菜单
     * @return
     */
    @ApiOperation(value = "获取当前用户的导航菜单",notes = "获取当前用户的导航菜单")
    @GetMapping("/navMenuList")
//    @PreAuthorize("hasAuthority('system:menu:list')")
    public MyResult navMenuList(Principal principal){
        Map<String,Object> resultMap=new HashMap<>();
        SysUser currentUser = sysUserService.getUserByUsername(principal.getName());

        // 获取当前用户拥有的权限菜单
        // 获取角色
        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + currentUser.getId()));

        // 获取菜单权限
        Set<SysMenu> menuSet = new HashSet<SysMenu>();
        for(SysRole sysRole:roleList){
            List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + sysRole.getId()));
            for(SysMenu sysMenu:sysMenuList){
                menuSet.add(sysMenu);
            }
        }

        List<SysMenu> sysMenuList = new ArrayList<>(menuSet); // 转成集合List

        sysMenuList.sort(Comparator.comparing(SysMenu::getOrderNum));  // 排序

        List<SysMenu> navMenuList = sysMenuService.buildTreeMenu(sysMenuList); // 构造菜单树

        resultMap.put("navMenuList",navMenuList);

        return MyResult.success(resultMap);
    }

    @ApiOperation(value = "菜单列表",notes = "菜单列表")
    @GetMapping("/list")
//    @PreAuthorize("hasAuthority('system:menu:query')")
    public MyResult list(){
        // 查询所有菜单信息
        List<SysMenu> menuList=sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        return MyResult.success().put("treeMenu",sysMenuService.buildTreeMenu(menuList));
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询",notes = "根据id查询")
    @GetMapping("/{id}")
//    @PreAuthorize("hasAuthority('system:menu:query')")
    public MyResult findById(@PathVariable(value = "id")Long id){
        SysMenu sysMenu = sysMenuService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("sysMenu",sysMenu);
        return MyResult.success(map);
    }

    /**
     * 添加或者修改
     * @param sysMenu
     * @return
     */
    @ApiOperation(value = "添加或者修改",notes = "添加或者修改")
    @PostMapping("/saveAndUpate")
//    @PreAuthorize("hasAuthority('system:menu:add')"+"||"+"hasAuthority('system:menu:edit')")
    public MyResult saveAndUpdate(@RequestBody @Valid SysMenu sysMenu){
        if(sysMenu.getId()==null || sysMenu.getId()==-1){
            sysMenu.setCreateTime(new Date());
            sysMenuService.save(sysMenu);
        }else{
            sysMenu.setUpdateTime(new Date());
            sysMenuService.updateById(sysMenu);
        }
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }



    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除",notes = "删除")
    @GetMapping("/delete/{id}")
//    @PreAuthorize("hasAuthority('system:menu:delete')")
    public MyResult delete(@PathVariable(value = "id")Long id){
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if(count>0){
            return MyResult.error("请先删除子菜单！");
        }
        sysMenuService.removeById(id);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }

}
